<?php
/**
 * 常用操作
 * 
 * @author ShuangYa
 * @package APIGateway
 * @category Library
 * @link https://www.sylingd.com/
 * @copyright Copyright (c) 2018 ShuangYa
 * @license https://www.sylibs.com/go/apigateway/license
 */
namespace ea\library;

use yesf\Yesf;
use yesf\library\Plugin;
use yesf\library\Swoole;
use ea\model\Config;

class Utils {
	/**
	 * 格式化WebAPI的返回结果
	 * 
	 * @access public
	 * @param array $result
	 * @return string
	 */
	public static function getWebApiResult($result = []) {
		if (isset($result['error'])) {
			return json_encode([
				'success' => FALSE,
				'error' => $result['error']
			]);
		} else {
			$result['success'] = TRUE;
			return json_encode($result);
		}
	}
	/**
	 * 生成UUID
	 * 
	 * @access public
	 * @param int $length
	 * @return string
	 */
	public static function generateUniqueId($length = 24) {
		static $i = 0;
		$i == 0 && $i = mt_rand(1, 0x7FFFFF);
		$r = sprintf('%08x%06x%04x%06x',
			//4-byte value representing the seconds since the Unix epoch
			time() & 0xFFFFFFFF,
			//3-byte machine identifier
			crc32(substr((string)gethostname(), 0, 256)) >> 8 & 0xFFFFFF,
			//2-byte process id
			Swoole::getSwoole()->worker_pid & 0xFFFF,
			//3-byte counter, starting with a random value
			$i = $i > 0xFFFFFE ? 1 : $i + 1
		);
		// if length is more than 24, append some random words
		while (strlen($r) < $length) {
			$r .= ord(mt_rand(65, 90) + (mt_rand(0, 1) === 1 ? 32 : 0));
		}
		return $r;
	}
	/**
	 * 获取随机字符串
	 * 
	 * @access public
	 * @param int $length
	 * @return string
	 */
	public static function randStr($length) {
		$str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		return substr(str_shuffle($str), 0, $length);
	}
	public static function getCookieName($name) {
		return Config::getInstance()->read('cookie_prefix') . $name;
	}
}